from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.

from .. import models
from django.core.urlresolvers import reverse
import os
from . viewsindex import uploads
from web.settings import BASE_DIR
from django.contrib.auth.decorators import permission_required


@permission_required('myadmin.show_order',raise_exception = True)
# 订单列表
def ordersindex(request):
    # 获取所有的数据
    datas = models.Order.objects.filter().exclude(status=4).order_by('id')
     # 获取搜索类别和关键字
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断是否有搜索类型
        if types == 'status':
            arr = {'未支付':0,'待发货':1,'待收货':2,'待评价':3}
            datas = datas.filter(status=arr[keywords])
        # else:
        elif types == 'shouhuoren':
            datas = datas.filter(shouhuoren__contains=keywords)
        elif types == 'shouhuophone':
            datas = datas.filter(shouhuophone__contains=keywords)
        elif types == 'shouhuoaddress':
            datas = datas.filter(shouhuoaddress__contains=keywords)  
        
    
     # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(datas,10)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p',1)
    # 获取当前页的数据
    orderslist = paginator.page(p)
    # 分配数据
    context = {'orderslist':orderslist}
    # 加载模板
    return render(request,'myadmin/orders/index.html',context)

# 订单详情
def indexinfo(request):
    # 接收订单编号
    oid = request.GET.get('oid')
    # 获取该商品的订单对象
    order = models.Order.objects.get(id=oid)
    # 获取对应的订单商品信息
    orderinfo = models.OrderInfo.objects.filter(orderid=order)
    print(orderinfo)
    # 分配数据
    context = {'orderinfolist':orderinfo}

    return render(request,'myadmin/orders/indexinfo.html',context)



@permission_required('myadmin.edit_order',raise_exception = True)
# 订单状态需求
def statusedit(request):
    try:
        # 获取订单编号和修改后的状态
        oid = request.GET.get('oid')
        status = request.GET.get('status')
        print(oid,status)
        # 获取该商品的订单对象
        ob = models.Order.objects.get(id=oid)
        ob.status = status
        ob.save()
        return JsonResponse({'error':0,'msg':'修改成功！'})
    except:
        return JsonResponse({'error':1})


